package com.kly.msg.consumer;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import com.kly.msg.constant.ApiRedisKeys;
import com.kly.msg.serviceImpl.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;
import java.util.concurrent.ExecutionException;

@Component
public class UserOperationIntervalConsumer {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisService redisService;


    private static final long expireInSeconds = 1000L;

    private static Thread onLineThread;

    @PostConstruct
    private void offlineConsumer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    if (redisService.setNX(ApiRedisKeys.USER_OPERATION_INTERVAL_LOCK.getValue(), "userOperationIntervalLock",
                            expireInSeconds, "userOperationIntervalLock")) {
                        Set<String> tasks = redisService.getDelayTask(
                                ApiRedisKeys.USER_OPERATION_INTERVAL.getValue(), "userOperationInterval");
                        //从有序集合中获取最早到达预定时间的任务
                        if (tasks != null && !tasks.isEmpty()) {
                            messagePush(tasks);
                            redisService.delDelayTask(
                                    ApiRedisKeys.USER_OPERATION_INTERVAL.getValue(), tasks, "userOperationInterval");
                        }
                    }

                } catch (Exception e) {
                    logger.error("An error occurred: ", e);
                } finally {
                    try {
                        redisService.del(ApiRedisKeys.USER_OPERATION_INTERVAL_LOCK.getValue(), "userOperationIntervalLock");
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                        break;
                    }
                }
            }
        });
        thread.start();

        onLineThread = thread;

    }

    public void interrupt() {
        if (onLineThread != null) {
            onLineThread.interrupt();
        }
    }

    public void messagePush(Set<String> tasks) {
        logger.info("userOperationInterval set: " + tasks + " current time：" + System.currentTimeMillis() / 1000);
        for (String userCode : tasks) {
            try {
                String userToken = redisService.getString(ApiRedisKeys.USER_FIREBASE_TOKEN.getValue(),
                        userCode);
                logger.info("user_firebase_token : key-" + RedisService.format(ApiRedisKeys.USER_FIREBASE_TOKEN.getValue(),
                        userCode) + ", value: " + userToken);
                if (userToken != null) {
                    Notification notification = Notification.builder()
                            .setTitle("")
                            .setBody("")
                            .setImage("").build();


                    //type 1 回复消息  2普通照片  3私密照片  4普通视频  5私密视频 6wlm喜欢
                    //isNotification true 通知栏消息  false应用内消息
                    //targetId 目标的userCode
                    //imageUrl 对方发送的图片或者视频链接
                    // Build a message
                    Message message = Message.builder()

                            .putData("type", "10")
                            .putData("userCode", userCode)
                            .putData("isNotification", "false")
//                        .putData("targetId", "12313")
//                        .putData("imageUrl", "http://t15.baidu.com/it/u=1691320874,470802157&fm=224&app=112&f=JPEG?w=500&h=500")
                            .setToken(userToken)
//                        .setNotification(notification)
                            .build();
                    String response = FirebaseMessaging.getInstance().sendAsync(message).get();
                    logger.info("userOperationInterval push: " + response);
                }
            } catch (Exception e) {
                logger.error("An error occurred: ", e);
                redisService.del(ApiRedisKeys.USER_FIREBASE_TOKEN.getValue(),
                        userCode);
            }

        }
    }

}
